package com.lfg.leetcode.leetcode0;

/**
 * 给定一个字符串 s，找到 s 中最长的回文子串
 */
public class No8Atoi {

    public static void main(String[] args) {
        System.out.println(atoi(" ++1"));
//        System.out.println(convert("0123456789012345678901234567890", 4));
//        System.out.println(convert("PAYPALISHIRING", 4));
    }


    public static int atoi(String str) {
        if (null == str || "".equals(str)) {
            return 0;
        }
        int index = 0;
        int length = str.length();
        while (index < length && (str.charAt(index) == ' ')) {
            index++;
        }
        boolean isAdd = false;
        if (index < length && (str.charAt(index) == '+')) {
            index++;
            isAdd = true;
        }
        boolean isNagate = false;
        if (index < length && (str.charAt(index) == '-')) {
            index++;
            isNagate = true;
        }
        while (index < length && str.charAt(index) == '0') {
            index++;
        }
        if (isAdd && isNagate) {
            return 0;
        }
        int pos = 0;
        Long ret = 0l;
        while (index < length && str.charAt(index) >= '0' && str.charAt(index) <= '9') {
            ret = ret * 10 + str.charAt(index) - '0';
            index++;
            pos++;
        }
        if (pos > 16 && isNagate) {
            return Integer.MIN_VALUE;
        }
        if (pos > 16 && !isNagate) {
            return Integer.MAX_VALUE;
        }
        if (isNagate) {
            ret = 0 - ret;
        }
        if (ret < Integer.MIN_VALUE) {
            return Integer.MIN_VALUE;
        }
        if (ret > Integer.MAX_VALUE) {
            return Integer.MAX_VALUE;
        }

        return ret.intValue();
    }
}
